package com.nikanbujian.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nikanbujian.reggie.common.CustomException;
import com.nikanbujian.reggie.dto.SetmealDto;
import com.nikanbujian.reggie.entity.Setmeal;
import com.nikanbujian.reggie.entity.SetmealDish;
import com.nikanbujian.reggie.mapper.SetmealMapper;
import com.nikanbujian.reggie.service.ISetmealDishService;
import com.nikanbujian.reggie.service.ISetmealService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 套餐 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-08-20
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements ISetmealService {

    @Autowired
    private ISetmealDishService iSetmealDishService;
    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        setmealDishes=setmealDishes.stream().map((item) ->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        iSetmealDishService.saveBatch(setmealDishes);
    }

    @Override
    public void delete(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,1);
        int count = this.count(lambdaQueryWrapper);
        if (count>0){
            throw new CustomException("当前套餐在售，无法删除");
        }
        this.removeByIds(ids);
        LambdaQueryWrapper<SetmealDish> setmealDishLambdaQueryWrapper=new LambdaQueryWrapper<>();
        setmealDishLambdaQueryWrapper.in(SetmealDish::getSetmealId,ids);
        iSetmealDishService.remove(setmealDishLambdaQueryWrapper);
    }
}
